package com.upu173.music.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.andbase.library.app.base.AbBaseFragment;
import com.andbase.library.asynctask.AbTask;
import com.andbase.library.asynctask.AbTaskItem;
import com.andbase.library.asynctask.AbTaskObjectListener;
import com.andbase.library.cache.AbImageCache;
import com.andbase.library.utils.AbAnimationUtil;
import com.andbase.library.utils.AbLogUtil;
import com.upu173.music.R;
import com.upu173.music.activity.MusicBaseActivity;
import com.upu173.music.activity.MusicPlayActivity;
import com.upu173.music.activity.MusicMainActivity;
import com.upu173.music.global.PlayerData;
import com.upu173.music.model.PlayList;
import com.upu173.music.model.SongTag;
import com.upu173.music.service.MusicPlayerService;
import com.upu173.music.utils.MusicControler;
import com.upu173.music.utils.MusicUtil;
import java.util.List;


public class MusicBarFragment extends AbBaseFragment {

    private MusicBaseActivity activity;

    private SeekBar seekBar;
    private ImageView playButton,nextButton;
    private TextView barName,barUser;
    private LinearLayout barBlankArea;
    private ImageView barImage;
    private AbImageCache cache;
    private boolean isPageStop = false;
    private String currentPlayPath = null;
    private Handler handlerSeekBar = new Handler();
    private Runnable runnableSeekBar = new Runnable() {
        @Override
        public void run() {

           if(!MusicPlayerService.playerManagerReceiver.filePath.equals(currentPlayPath)){
               initMusicBarData();
           }

           int currentTime = MusicPlayerService.playerManagerReceiver.getCurrentPosition();
           if(currentTime == 0 || currentTime <=  MusicPlayerService.playerManagerReceiver.getDuration() - 3000){
                if(!isPageStop){
                    seekBar.setProgress(currentTime);
                    seekBar.setMax(MusicPlayerService.playerManagerReceiver.getDuration());
                }
                handlerSeekBar.postDelayed(this,500);
           }

        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.music_bar_fragment, container, false);

        activity = (MusicBaseActivity)this.getActivity();
        cache = AbImageCache.getInstance(activity);

        initPlayBarView(rootView);

        return rootView;
    }


    private void initPlayBarView(View rootView) {

        playButton = (ImageView)rootView.findViewById(R.id.bar_play);
        nextButton = (ImageView)rootView.findViewById(R.id.bar_next);
        seekBar = (SeekBar)rootView.findViewById(R.id.seek_bar);
        barName = (TextView)rootView.findViewById(R.id.bar_name);
        barUser = (TextView)rootView.findViewById(R.id.bar_user);
        barImage = (ImageView)rootView.findViewById(R.id.bar_image);
        barBlankArea = (LinearLayout)rootView.findViewById(R.id.bar_blank_area);
        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(PlayerData.playList.size() == 0){
                    return;
                }

                if(PlayerData.getCurrentPlaySong() == null){
                    playSong(0);
                }else{
                    if(MusicPlayerService.playerManagerReceiver!=null && !MusicPlayerService.playerManagerReceiver.isPlaying()){
                        startPlay(PlayerData.getCurrentPlaySong());
                    }else{
                        pausePlay();
                    }
                }

            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextSong();
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    if(MusicPlayerService.playerManagerReceiver.isPlaying()){
                        MusicControler.seekToReceiver(activity,progress);
                    }

                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        barImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(PlayerData.getCurrentPlaySong()!=null){
                    Intent intent = new Intent(activity,MusicPlayActivity.class);
                    intent.putExtra("songName",PlayerData.getCurrentPlaySong().getName());
                    intent.putExtra("songPath",PlayerData.getCurrentPlaySong().getPath());
                    startActivity(intent);
                }
            }
        });
        barBlankArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(PlayerData.getCurrentPlaySong()!=null){
                    Intent intent = new Intent(activity,MusicPlayActivity.class);
                    intent.putExtra("songName",PlayerData.getCurrentPlaySong().getName());
                    intent.putExtra("songPath",PlayerData.getCurrentPlaySong().getPath());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        isPageStop = false;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initMusicBarData();
            }
        },500);

    }

    @Override
    public void onStop() {
        isPageStop = true;
        barImage.clearAnimation();
        super.onStop();
    }

    public void initMusicBarData(){
        handlerSeekBar.removeCallbacks(runnableSeekBar);
        if(MusicPlayerService.playerManagerReceiver!=null && MusicPlayerService.playerManagerReceiver.isPlaying()){
            startPlayUI(PlayerData.getCurrentPlaySong());
        }else{
            if(PlayerData.getCurrentPlaySong()!= null){
                updateMusicBar(PlayerData.getCurrentPlaySong());
                pausePlayUI();
            }
        }
    }

    public void updateMusicBar(final PlayList song){

        if(song.getPath().equals(currentPlayPath)){
            return;
        }

        currentPlayPath = song.getPath();
        barName.setText(song.getName());
        barUser.setText(song.getSinger());

        if(cache.containKey(song.getPath())){
            Bitmap bitmap =  cache.getBitmap(song.getPath());
            if(bitmap!= null){
                barImage.setImageBitmap(bitmap);
            }else{
                barImage.setImageResource(R.drawable.ic_music_song);
            }

        }else{

            AbTask task = AbTask.newInstance();
            AbTaskItem item = new AbTaskItem();
            item.setListener(new AbTaskObjectListener<SongTag>() {
                @Override
                public SongTag getObject() {
                    return MusicUtil.getSongTag(activity,song.getPath(),true);
                }

                @Override
                public void update(SongTag songTag) {
                    cache.putBitmap(song.getPath(),songTag.getBitmap());
                    if(songTag.getBitmap()!= null){
                        barImage.setImageBitmap(songTag.getBitmap());
                    }else{
                        barImage.setImageResource(R.drawable.ic_music_song);
                    }
                }
            });
            task.execute(item);

        }

        if(activity instanceof MusicMainActivity){
            MusicMainActivity musicMainActivity = (MusicMainActivity)activity;
            if(musicMainActivity.playListFragment!=null){
                musicMainActivity.playListFragment.recyclerViewAdapter.notifyDataSetChanged();
            }
        }

    }

    public void startPlay(PlayList playSong){
        startPlayUI(playSong);
        if(PlayerData.getCurrentPlaySong()==null || !playSong.getPath().equals(PlayerData.getCurrentPlaySong().getPath())){
            PlayerData.setCurrentPlaySong(playSong);
            MusicControler.startPlayReceiver(activity,playSong.getPath());
        }else{
            MusicControler.startPlayReceiver(activity,null);
        }
    }

    public void pausePlay(){
        pausePlayUI();
        MusicControler.pausePlayReceiver(activity);
    }

    public void startPlayUI(PlayList playSong){
        updateMusicBar(playSong);
        handlerSeekBar.postDelayed(runnableSeekBar,200);
        playButton.setImageResource(R.drawable.ic_music_bar_pause_selector);
        AbAnimationUtil.playRotateAnimation(barImage,5000, Animation.INFINITE, Animation.RESTART,new LinearInterpolator());
    }

    public void pausePlayUI(){
        handlerSeekBar.removeCallbacks(runnableSeekBar);
        playButton.setImageResource(R.drawable.ic_music_bar_play_selector);
        barImage.clearAnimation();
    }

    public void nextSong(){
        if(PlayerData.playList.size() > PlayerData.position + 1){
            playSong( PlayerData.position +1);
        }else{
            playSong(PlayerData.position);
        }
    }

    public void playSong(int position){
        if(PlayerData.getCurrentPlaySong()!=null){
            AbLogUtil.e(activity.pageClassName,"正在播放的歌曲：" + PlayerData.getCurrentPlaySong().getName());
        }else{
            AbLogUtil.e(activity.pageClassName,"正在播放的歌曲：无");
        }

        PlayList playSong = PlayerData.playList.get(position);

        AbLogUtil.e(activity.pageClassName,"开始播放下一首歌曲：" + playSong.getName());
        if(PlayerData.getCurrentPlaySong()!=null && PlayerData.getCurrentPlaySong().getPath().equals(playSong.getPath())){
            AbLogUtil.e(activity.pageClassName,"这是同一首歌曲");
            return;
        }
        playSong(playSong);
    }

    public void playSong(PlayList playSong){
        if(MusicPlayerService.playerManagerReceiver.isPlaying()){
            pausePlayUI();
        }

        startPlay(playSong);

    }

    public void initPlayList(List<PlayList> items){
        PlayerData.playList.clear();
        PlayerData.playList.addAll(items);
    }

    public void releaseAll(){
        handlerSeekBar.removeCallbacks(runnableSeekBar);
        MusicControler.releasePlay(activity);
    }

}
